﻿using Central.Linq.MvcJson.Engine;
using SampleData;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.Mvc;

namespace Central.Linq.MvcJson.Controllers {

    public class HomeController : Controller {
        private List<Person> _people;

        public HomeController() {
            _people = People.GetPeople();
        }

        public ActionResult Index() {
            return View();
        }

        public ActionResult Person() {
            return View();
        }

        public ActionResult Attempt3() {
            return View();
        }

        [OutputCache(Duration = 0, NoStore = true)]
        public ActionResult LoadPersons(JsonQueryParams queryParams) {
            QueryParams qp = new QueryParams(new PersonInfoManager().DefaultFieldManager);
            if (queryParams != null) {
                if (queryParams.Filters != null && queryParams.Filters.FilterParams.Count > 0) {
                    qp.Filters = queryParams.Filters.CreateFilterManager;
                }
                if (queryParams.Sorters != null && queryParams.Sorters.SortParams.Count > 0) {
                    qp.Sorters = queryParams.Sorters.CreateSortManager;
                }
                if (queryParams.Groups != null && queryParams.Groups.GroupParams.Count > 0) {
                    string[] groups = queryParams.Groups.GroupParams.Select(x => x.FieldName).ToArray();
                    qp.Groups = new PersonInfoManager().CreateGroupManager(groups, queryParams.Groups.FieldNameForCount);
                }
            }
            var data = _people.AsQueryable().PrepareQuery<Person, PersonViewModel>(qp);

            var result = data.Select(x => new {
                Age = x.Age,
                Country = x.Country.ToString(),
                Description = x.Description,
                Gender = x.Gender,
                IsMember = x.IsMember,
                MemberDate = x.MemberDate,
                Name = x.Name,
                Weight = x.Weight
            });
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        public JsonResult PersonFields() {
            var fieldsinfo = new PersonInfoManager().FieldInformations;
            var result = fieldsinfo.Select(x => new { Name = x.Name, FilterType = x.FilterType, DisplayName = x.DisplayName });
            return Json(result.ToArray(), JsonRequestBehavior.AllowGet);
        }

        //public JsonResult ChangeOperators(int type) {
        //	IEnumerable<OperatorName> selected = InfoHelper.ApplicableFilterOperators(type);
        //	return Json(selected.ToArray(), JsonRequestBehavior.AllowGet);
        //}
    }
}